<template>
  <!--三级联动表单  :inline代表行内表单，代表一行有多个表单元素；第一步静态，第二步搞定动态：书写api接口 
  :model="cForm"代表数据收集到cFform    
  
  -->
  <el-form :inline="true" :model="cForm" class="demo-form-inline">
    <el-form-item label="一级分类">
      <!--一级分类动态展示   v-for遍历1级  c in category1List  在什么时间获取数据需要绑定一个事件handle1 -->
      <el-select :disabled="show" v-model="cForm.category1Id" placeholder="请选择" @change="handler1">
        <el-option :label="c1.name" :value="c1.id" v-for="(c1, index) in list1" :key="c1.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="二级分类">
      <!--与1级一样需要遍历-->
      <el-select :disabled="show" v-model="cForm.category2Id" placeholder="请选择" @change="handler2">
        <el-option :label="c2.name" :value="c2.id" v-for="(c2, index) in list2" :key="c2.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="三级分类">
      <el-select :disabled="show" v-model="cForm.category3Id" placeholder="请选择" @change="handler3">
        <el-option :label="c3.name" :value="c3.id" v-for="(c3, index) in list3" :key="c3.id"></el-option>
      </el-select>
    </el-form-item>
  </el-form>
</template>

<script>

export default {
  name: 'CategorySelector',
  props:['show'],
  data() {
    return {
      list1: [],
      list2: [],
      list3: [],
      cForm: {//收集1、2/3级的id
        category1Id: '',
        category2Id: '',
        category3Id: '',
      },
       disabled: false, // 下拉列表是否禁用
    }
  },

  //当组件挂载完毕向服务器发请求，获取相应数据
  mounted() {
    this.getCategory1List();
  },

  methods: {
    /* 
    获取一级分类列表显示
    */
    async getCategory1List() {
      //获取一级分类的请求
      let result = await this.$API.attr.reqCategory1List();
      if (result.code == 200) {
        this.list1 = result.data;
      };
    },
    //一级分类
    async handler1() {
      // 重置二级与三级分类相关数据，重新选择要清空掉
      
      this.category2List = [];
      this.category3List = [];
      this.cForm.category2Id = '';
      this.cForm.category3Id = '';
      const { category1Id } = this.cForm;
      this.$emit('getCategoryId', { categoryId: category1Id, level: 1 });
      
      let result = await this.$API.attr.reqCategory2List(category1Id);
      if (result.code == 200) {
        this.list2 = result.data;
      }
    },
    //2级分类
    async handler2() {
      // 重置三级列表相关数据
      this.category3List = [];
      this.cForm.category3Id = '';
      
      const { category2Id } = this.cForm;
      this.$emit('getCategoryId', { categoryId: category2Id, level: 2 });
      
      let result = await this.$API.attr.reqCategory3List(category2Id);
      if (result.code == 200) {
        this.list3 = result.data;
      }
    },
    //3级分类
    async handler3() {
      const { category3Id } = this.cForm;
      await this.$emit('getCategoryId', { categoryId: category3Id, level: 3 })
    }
  },
};
</script>




<style scoped>

</style>